﻿using System;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Drawing;

namespace Daemon
{
    public partial class Form1 : Form
    {
        private static string path;
        private static string file;
        private static string deleted;
        private static string backup;
        private static string interval = "2";
        private static OpenFileDialog ofd = new OpenFileDialog();

        public Form1()
        {
            InitializeComponent();
            try
            {
                ofd.InitialDirectory = ConfigurationManager.AppSettings["init.dir"].ToString().Trim();
            }
            catch { }
            try
            {
                interval = ConfigurationManager.AppSettings["interval.minutes"].ToString().Trim();
            }
            catch { }
            timer1.Interval = int.Parse(interval) * 60 * 1000;
        }

        // locate
        private void button1_Click(object sender, EventArgs e)
        {
            DialogResult res = ofd.ShowDialog();
            if (res == DialogResult.OK)
            {
                timer1.Stop();
                checkBox1.Checked = false;
                textBox1.Text = ofd.FileName;
                string[] segs = textBox1.Text.Split('\\');
                file = segs.Last();
                path = textBox1.Text.Replace(file, "");
                doLog("set path=" + path);
                doLog("set file=" + file);
                deleted = path + "deleted";
                backup = path + "backup"; // saves before being overwrited
                Directory.CreateDirectory(deleted);
                Directory.CreateDirectory(backup);
                doRefresh();
            }
        }

        private void doRefresh()
        {
            flowLayoutPanel1.Controls.Clear(); // 先清空
            string[] items = Directory.GetFiles(path, file + "_??_??_??").Reverse().Take(11).ToArray(); // 取最近的11个
            foreach (string item in items)
            {
                string serial = Regex.Split(item, file + "_").Last(); // like 22_12_34
                Button button = new Button();
                button.Text = serial;
                button.Name = serial;
                button.Click += new EventHandler(itemHandler);
                flowLayoutPanel1.Controls.Add(button);
            }
        }

        private void itemHandler(object sender, EventArgs e)
        {
            var btn = (Button)sender;
            doRestore(btn.Text);
        }

        private void doRestore(string item)
        {
            DialogResult result = MessageBox.Show(" to restore: " + item + " ?", "Confirm", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (result == DialogResult.OK)
            {
                string suffix = DateTime.Now.ToString("_HH_mm_ss");
                string backupFileName = file + suffix;
                File.Move(path + file, backup + "\\" + backupFileName);
                doLog("backup to " + backupFileName);
                File.Copy(path + file + "_" + item, path + file);
                doLog("resotred " + file + "_" + item);
            }
        }

        // delete all
        private void button4_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(file)) return; // 未选文件之前，不响应
            string[] files = Directory.GetFiles(path, file + "_??_??_??");
            foreach (string fileToDel in files)
            {
                doDelete(fileToDel);
            }
            doRefresh();
        }

        // manual save
        private void button3_Click(object sender, EventArgs e)
        {
            doSave(false);
        }
        private void doSave(bool isAuto)
        {
            if (string.IsNullOrEmpty(file)) return; // 未选文件之前，不响应
            string suffix = DateTime.Now.ToString("_HH_mm_ss");
            string newFile = path + file + suffix;
            File.Copy(path + file, newFile, true);
            string msg = "saved to " + file + suffix;
            doLog((isAuto ? "[AUTO] " : "") + msg);
            doRefresh();
        }

        // toggle auto-save
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(file))
            {
                return; // 未选文件之前，不响应
            }
            if (checkBox1.Checked)
            {
                startAutoSave();
            }
            else
            {
                stopAutoSave();
            }
        }
        private void startAutoSave()
        {
            // timer1.Interval = 5000; // for dev
            doSave(true);
            timer1.Start();
            doLog("[AUTO] start auto save");
        }
        private void stopAutoSave()
        {
            timer1.Stop();
            doLog("[AUTO] auto save is off");
        }

        private void doLog(string msg)
        {
            string now = DateTime.Now.ToString("MM-dd HH:mm:ss ");
            richTextBox1.AppendText(now + msg + "\r\n");
            richTextBox1.ScrollToCaret();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            doSave(true);
        }

        private void doDelete(string fileToDel)
        {
            string fileName = fileToDel.Split('\\').Last();
            File.Move(fileToDel, deleted + "\\" + fileName);
            doLog("deleted " + fileName);
        }
    }
}
